<?php

namespace App\Http\Controllers\Home;

use App\Exceptions\BizException;
use App\Http\Controllers\Controller;
use App\Model\Agent;
use App\Model\City;
use App\Model\Province;
use App\Model\UserAddress;
use App\Model\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth']);
    }

    // 个人中心
    public function index(Request $request)
    {
        $user = Auth::user();
        $agent = $request->agent;
        $params = $request->all();
        return view("home.{$agent['tpl_id']}.user", [
            'params' => $params,
            'agent' => $agent,
            'user' => Users::find($user->id),
        ]);
    }

    public function profile(Request $request)
    {
        $user = Auth::user();
        $agent = $request->agent;
        return view("home.{$agent['tpl_id']}.profile", [
            'agent' => $agent,
            'user' => $user,
        ]);
    }

    public function userSet(Request $request)
    {
        $user = Auth::user();
        $agent = $request->agent;
        return view("home.{$agent['tpl_id']}.user-set", [
            'agent' => $agent,
            'user' => $user,
        ]);
    }

    public function changeName(Request $request)
    {
        $user = Auth::user();
        if ($request->getMethod() == 'POST') {
            Users::where('id', $user->id)->update(['nickname' => $request->input('nickname')]);
            return '';
        } else {
            return view('home.' . $request->agent->tpl_id . '.change-name', [
                'user' => $user,
            ]);
        }
    }

    public function changeInfo(Request $request)
    {
        $user = Auth::user();
        Users::where('id', $user->id)->update([$request->input('field') => $request->input('val')]);
        return '';
    }

    public function changePwd(Request $request)
    {
        $user = Auth::user();
        if ($request->getMethod() == 'POST') {
            try {
                $this->validate($request, [
                    'password' => 'required',
                    'new_password' => 'required',
                    're_password' => 'required|same:new_password',
                ], [
                    'password.required' => '旧密码必填',
                    'new_password.required' => '新密码必填',
                    're_password.required' => '确认密码必填',
                    're_password.same' => '新密码与确认密码不一致',
                ]);

                $user = Auth::user();
                $params = $request->all();

                $res = Auth::attempt([
                    'username' => $user->username,
                    'password' => $params['password'],
                ]);
                if (!$res)
                    throw new BizException('原密码不正确');
                if (!preg_match('/^\w{6,}$/', $params['new_password']))
                    throw new BizException('新密码至少是6位的字母数字组合');

                Users::where('id', $user->id)->update(['password' => bcrypt($params['new_password'])]);
            } catch (ValidationException $e) {
                return response()->json(['status' => 0, 'info' => $e->validator->errors()->first()]);
            } catch (BizException $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
            return response()->json(['status' => 1, 'info' => '修改成功']);
        } else {
            return view('home.' . $request->agent->tpl_id . '.change-pwd', [
                'user' => $user,
            ]);
        }
    }

    public function addressList(Request $request)
    {
        $user = Auth::user();
        $list = UserAddress::where('uid', $user->id)->get();
        $cityIds = [];
        foreach ($list as $v) {
            $cityIds[] = $v['city_id'];
        }
        return view('home.' . $request->agent->tpl_id . '.address-list', [
            'list' => $list,
            'provinces' => Province::pluck('name', 'id')->toArray(),
            'cities' => City::whereIn('id', $cityIds)->pluck('name', 'id')->toArray(),
        ]);
    }

    public function address(Request $request)
    {
        $user = Auth::user();
        if ($request->getMethod() == 'POST') {
            try {
                $this->validate($request, [
                    'name' => 'required',
                    'mobile' => 'required|regex:/^1\d{10}$/',
                    'province_id' => 'required',
                    'city_id' => 'required',
                    'district' => 'required',
                    'detail' => 'required',
                ], [
                    'name.required' => '收货人姓名必填',
                    'mobile.required' => '收货人手机号必填',
                    'mobile.regex' => '请填写正确的手机号',
                    'province_id.required' => '请选择省份',
                    'city_id.required' => '请选择市',
                    'district.required' => '区域必填',
                    'detail.required' => '详细地址必填',
                ]);

                $user = Auth::user();
                $params = $request->all();

                if (empty($request->input('id'))) {
                    $params['uid'] = $user->id;
                    UserAddress::create($params);
                } else {
                    UserAddress::where('id', $request->input('id'))->update($params);
                }
            } catch (ValidationException $e) {
                return response()->json(['status' => 0, 'info' => $e->validator->errors()->first()]);
            } catch (BizException $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
            return response()->json(['status' => 1, 'info' => '保存成功']);
        } else {
            $address = $request->input('id') ? UserAddress::find($request->input('id')) : ['mobile' => $user->username];
            return view('home.' . $request->agent->tpl_id . '.address', [
                'user' => $user,
                'provinces' => Province::pluck('name', 'id')->toArray(),
                'address' => $address,
            ]);
        }
    }

    public function addressSet(Request $request)
    {
        $user = Auth::user();
        UserAddress::where('uid', $user->id)->update(['is_default' => 0]);
        UserAddress::where('id', $request->input('id'))->update(['is_default' => 1]);
        return '';
    }

    public function addressDel(Request $request)
    {
        UserAddress::where('id', $request->input('id'))->delete();
        return '';
    }
}